package top.jandmla.excel.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class FileDownLoad {
    /***
     * 文件下载
     * @param filename 需要下载文件的绝对路径
     * @param res HttpServletResponse
     */
    public static void download(String filename, HttpServletResponse res) {
        InputStream inputStream = null;
        OutputStream os = null;
        try {
            File file = FileUtils.getFile(filename);
            String name = file.getName();
            inputStream = FileUtils.openInputStream(file);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = IOUtils.toByteArray(inputStream);
            res.reset();
            res.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setContentType("application/octet-stream");
            os = res.getOutputStream();
            os.write(buffer);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                IOUtils.closeQuietly(inputStream);
            }
            if (os != null) {
                IOUtils.closeQuietly(os);
            }
            File file = FileUtils.getFile(filename);
            if (file.exists())
                FileUtils.deleteQuietly(file);
        }
    }
}
